import Vue from 'vue'
import VueRouter from 'vue-router'

import LayoutView from '../views/layout/LayoutView.vue'
import HomeView from '../views/layout/HomeView.vue'
import CategoryView from '../views/layout/CategoryView.vue'
import CartView from '../views/layout/CartView.vue'
import UserView from '../views/layout/UserView.vue'

import store from '@/store/index'

// 路由按需加载
const LoginView = () => import('../views/login/LoginView.vue')
const SearchView = () => import('../views/search/SearchView.vue')
const SearchListView = () => import('../views/search/SearchListView.vue')
const ProductDetailView = () => import('../views/product_detail/ProductDetailView.vue')
const PayView = () => import('../views/pay/PayView.vue')
const MyOrderView = () => import('../views/my_order/MyOrderView.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    name: 'root',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: LayoutView,
    redirect: '/home',
    children: [
      { path: '/home', component: HomeView },
      { path: '/category', component: CategoryView },
      { path: '/cart', component: CartView },
      { path: '/user', component: UserView }
    ]
  },
  {
    path: '/search',
    name: 'search',
    component: SearchView
  },
  {
    path: '/search-list',
    name: 'search list',
    component: SearchListView
  },
  {
    path: '/product-detail/:id',
    name: 'product detail',
    component: ProductDetailView
  },
  {
    path: '/pay',
    name: 'pay',
    component: PayView
  },
  {
    path: '/my-order',
    name: 'my order',
    component: MyOrderView
  }
]

const router = new VueRouter({
  routes
})

const NeedAuthUrls = [
  '/pay',
  '/my-order'
]

router.beforeEach((to, from, next) => {
  if (NeedAuthUrls.includes(to.path)) {
    const token = store.state.user.userInfo.token
    if (!token) {
      console.log('router.beforeEach', '没有登录，请登录')
      next('/login')
      return
    }
  }

  next()
})

export default router
